package com.hrms.hrms_security.component;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import com.hrms.common.utils.JwtUtils;
import com.hrms.common.utils.RedisUtil;
import com.hrms.common.utils.ResultMessage;
import com.hrms.hrms_security.vo.AccountUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功将jwt放入响应头
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    JwtUtils jwtUtils;
    @Resource
    RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        String name = authentication.getName();
        AccountUser loginUser = (AccountUser) authentication.getPrincipal();
        // 生成JWT，并放置到相应头2中
        long ttlMillis = 1000 * 60 * 60 * 24;
        String jwt = jwtUtils.createJWT(name,ttlMillis);
        httpServletResponse.setHeader(jwtUtils.getHeader(), jwt);
        redisUtil.setEx("login."+name, JSON.toJSONString(loginUser),ttlMillis, TimeUnit.MILLISECONDS);

        ResultMessage result = new ResultMessage(ResultMessage.Success,"SuccessLogin",jwt);

        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

